<template>
  <h1>响应式计算和监听</h1>
  <div class="v-flex" style="height: 100%; overflow: auto;">
    <div class="v-gap">
      count: {{ count }}
      <div v-for="(msg, i) of msgQueue" :key="i">{{ msg }}</div>
    </div>
    <div class="v-gap">
      number: {{ number }}
      <div v-for="(num, i) of numerQueue" :key="i">{{ num }}</div>
    </div>
    <div class="v-gap">
      age: {{ age }}
      <div v-for="(age, i) of ageQueue" :key="i">{{ age }}</div>
    </div>
    <div class="v-gap">
      min: {{ min }}
      <div v-for="(minq, i) of minQueue" :key="i">{{ minq }}</div>
    </div>
    <div class="v-gap">
      max: {{ max }}
      <div v-for="(maxq, i) of maxQueue" :key="i">{{ maxq }}</div>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, defineComponent, watchEffect } from "vue";
export default defineComponent({
  name: "reactiveComputedOrWatch",
  setup() {
    const count = ref(0);
    const number = ref(0);
    const age = ref(0);
    const min = ref(0);
    const max = ref(0);
    const msgQueue = ref<Array<string>>([]);
    const numerQueue = ref<Array<string>>([]);
    const ageQueue = ref<Array<string>>([]);
    const minQueue = ref<Array<string>>([]);
    const maxQueue = ref<Array<string>>([]);
    setInterval(() => {
      count.value += 1;
      number.value += 1;
      age.value += 1;
      min.value += 1;
      max.value += 1;
    }, 1000);
    // 1.不需要手动传入依赖
    // 2.每次初始化时会执行一次回调函数来自动获取依赖
    // 3.无法获取到原值，只能得到变化后的值
    watchEffect(() => {
      msgQueue.value.push(`count发生变化, 新值: ${count.value}`);
      numerQueue.value.push(`number发生变化, 新值: ${number.value}`);
      ageQueue.value.push(`age发生变化, 新值: ${age.value}`);
      minQueue.value.push(`min发生变化, 新值: ${min.value}`);
      maxQueue.value.push(`max发生变化, 新值: ${max.value}`);
    });
    return {
      count,
      msgQueue,
      number,
      numerQueue,
      age,
      ageQueue,
      min,
      minQueue,
      max,
      maxQueue,
    };
  },
});
</script>

<style scoped>
.v-gap {
  margin: 0 10px;
}
.v-flex {
  align-items: flex-start;
}
</style>
